// pages/admin/donation-manage/donation-manage.js
const { get, put } = require('../../../utils/request')
const { formatDate, showSuccess, showError, showConfirm } = require('../../../utils/util')

Page({
  data: {
    donationList: [],
    statusIndex: 0,
    statusList: ['全部状态', '待确认', '已确认', '已拒绝'],
    typeIndex: 0,
    typeList: ['全部类型', '医疗救助', '日常用品', '食物', '其他'],
    stats: {
      total: 0,
      totalAmount: 0,
      pending: 0,
      confirmed: 0
    },
    loading: false
  },

  onLoad() {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.loadDonationList()
  },

  onShow() {
    this.loadDonationList()
  },

  onPullDownRefresh() {
    this.loadDonationList(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载捐助列表
  loadDonationList(callback) {
    this.setData({ loading: true })

    const params = {}

    // 添加状态筛选
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusList[this.data.statusIndex]
    }

    // 添加类型筛选
    if (this.data.typeIndex > 0) {
      params.type = this.data.typeList[this.data.typeIndex]
    }

    get('/donation/list', params).then(res => {
      const donationList = res.data || []

      // 格式化时间和金额
      donationList.forEach(item => {
        item.createTime = formatDate(item.createTime)
        if (item.confirmTime) {
          item.confirmTime = formatDate(item.confirmTime)
        }
        item.amount = parseFloat(item.amount || 0).toFixed(2)
      })

      // 计算统计数据
      const stats = {
        total: donationList.length,
        totalAmount: donationList.reduce((sum, item) => sum + parseFloat(item.amount), 0).toFixed(2),
        pending: donationList.filter(item => item.status === '待确认').length,
        confirmed: donationList.filter(item => item.status === '已确认').length
      }

      this.setData({
        donationList,
        stats
      })
    }).catch(err => {
      showError('加载失败')
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value)
    })
    this.loadDonationList()
  },

  // 类型筛选
  onTypeChange(e) {
    this.setData({
      typeIndex: parseInt(e.detail.value)
    })
    this.loadDonationList()
  },

  // 刷新
  onRefresh() {
    this.loadDonationList()
  },

  // 确认捐助
  async confirmDonation(e) {
    const id = e.currentTarget.dataset.id

    try {
      await showConfirm('确定要确认这笔捐助吗？')
    } catch {
      return
    }

    // 弹出备注输入框
    wx.showModal({
      title: '确认备注',
      content: '',
      placeholderText: '请输入确认备注（可选）',
      editable: true,
      success: (res) => {
        if (res.confirm) {
          const confirmNote = res.content || '感谢您的爱心捐助！'

          // 使用正确的确认接口，传递查询参数
          const url = `/donation/confirm/${id}?status=已确认&confirmNote=${encodeURIComponent(confirmNote)}`

          put(url).then(res => {
            showSuccess('确认成功')
            this.loadDonationList()
          }).catch(err => {
            showError(err.msg || '确认失败')
          })
        }
      }
    })
  },

  // 拒绝捐助
  async rejectDonation(e) {
    const id = e.currentTarget.dataset.id

    try {
      await showConfirm('确定要拒绝这笔捐助吗？')
    } catch {
      return
    }

    // 弹出备注输入框
    wx.showModal({
      title: '拒绝原因',
      content: '',
      placeholderText: '请输入拒绝原因（必填）',
      editable: true,
      success: (res) => {
        if (res.confirm) {
          const confirmNote = res.content

          if (!confirmNote || !confirmNote.trim()) {
            showError('请输入拒绝原因')
            return
          }

          // 使用正确的确认接口，传递查询参数
          const url = `/donation/confirm/${id}?status=已拒绝&confirmNote=${encodeURIComponent(confirmNote.trim())}`

          put(url).then(res => {
            showSuccess('操作成功')
            this.loadDonationList()
          }).catch(err => {
            showError(err.msg || '操作失败')
          })
        }
      }
    })
  }
})
